package com.srxz.personnelsystem.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.srxz.personnelsystem.system.entity.DepartToPosition;
import com.srxz.personnelsystem.system.entity.Department;
import com.srxz.personnelsystem.system.entity.Position;
import com.srxz.personnelsystem.system.mapper.converter.PositionMapper;
import com.srxz.personnelsystem.system.mapper.dto.DepartmentDTO;
import com.srxz.personnelsystem.system.mapper.dto.PositionDTO;
import com.srxz.personnelsystem.system.repository.PositionRepository;
import com.srxz.personnelsystem.system.service.BaseService;
import com.srxz.personnelsystem.system.service.PositionService;
import com.srxz.personnelsystem.util.BackMessage;
import com.srxz.personnelsystem.util.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: PositionServiceImpl
 * @author: wgchao
 * @createTime: 2019/1/24 10:48 AM
 * @Description: TODO
 */
@Service
@Transactional
public class PositionServiceImpl extends BaseService<PositionDTO> implements PositionService {
    @Autowired
    private PositionRepository positionRepository;
    @Autowired
    private PositionMapper positionMapper;

    @Override
    public BackMessage save(PositionDTO positionDTO) {
        Position position = positionMapper.entity(positionDTO);
        position.setStatus(true);
        position.setCreateTime(new Date());
        //TODO 设置创建人

        position = positionRepository.save(position);
        return BackMessage.success().putData(positionMapper.dto(position));
    }

    @Override
    public BackMessage delete(PositionDTO positionDTO) {
        Position position = positionRepository.getOne(positionDTO.getId());
        position.setDeleteTime(new Date());
        //TODO 设置删除人

        position = positionRepository.save(position);
        return BackMessage.success().putData(positionMapper.dto(position));
    }

    @Override
    public BackMessage update(PositionDTO positionDTO) {
        Position position = positionMapper.entity(positionDTO);
        position.setLastUpdateTime(new Date());
        //TODO 设置更新人

        position = positionRepository.save(position);
        return BackMessage.success().putData(positionMapper.dto(position));
    }

    @Override
    public BackMessage search(String id) {
        Position position = positionRepository.getOne(id);
        return BackMessage.success().putData(positionMapper.dto(position));
    }

    @Override
    public BackMessage searchToPage(PageParam pageParam) {
        Pageable pageable = PageRequest.of(pageParam.getOffset(), pageParam.getLimit());

        Specification<Position> positionSpecification = new Specification<Position>() {
            @Override
            public Predicate toPredicate(Root<Position> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //设置查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (pageParam.getSearchCon() != null && !pageParam.getSearchCon().isEmpty()) {
                    for (Map.Entry<String, Object> km : pageParam.getSearchCon().entrySet()) {
                        String key = km.getKey();
                        Object val = km.getValue();
                        if ("pname".equals(key)) {//职位名称
                            if (val == null || val.toString().equals("")) {
                                continue;
                            }
                            Predicate p = criteriaBuilder.like(root.get("name").as(String.class), "%" + km.getValue().toString() + "%");
                            list.add(p);
                        }
                        if ("status".equals(key)) {//状态
                            if (val == null || val.toString().equals("")) {
                                continue;
                            }
                            Predicate p = criteriaBuilder.equal(root.get("status").as(Boolean.class), km.getValue().toString().equals("0")?true:false);
                            list.add(p);
                        }
                        if ("department".equals(key)) {//部门
                            if (val == null || val.toString().equals("")) {
                                continue;
                            }
                            Subquery subQuery = criteriaQuery.subquery(String.class);
                            Root fromUR = subQuery.from(DepartToPosition.class);
                            subQuery.select(fromUR.get("positionId")).where(criteriaBuilder.equal(fromUR.get("departmentId"), km.getValue().toString()));
                            Predicate p = criteriaBuilder.in(root.get("id")).value(subQuery);
                            list.add(p);
                        }
                    }
                }
                //未删除
                Predicate p1 = criteriaBuilder.isNull(root.get("deleteTime").as(ZonedDateTime.class));
                list.add(p1);

                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            }
        };

        //执行查询操作
        Page<Position> positions = positionRepository.findAll(positionSpecification, pageable);
        System.out.println(positions.getTotalElements());
        List<PositionDTO> positionDTOS = positions.getContent().stream().
                map(n -> {
                    PositionDTO positionDTO = positionMapper.dto(n);
                    extendCommon(positionDTO);
                    return positionDTO;
                }).collect(Collectors.toList());
        return BackMessage.success().putPageData(positions.getTotalElements(), positionDTOS);
    }

    @Override
    public BackMessage deleteList(List<PositionDTO> positionDTOS) {
        List<Position> positions = new ArrayList<>();
        if(positionDTOS!=null && !positionDTOS.isEmpty()){
            for(PositionDTO positionDTO:positionDTOS){
                Position position = positionRepository.getOne(positionDTO.getId());
                position.setDeleteTime(new Date());
                //TODO 设置删除人

                positions.add(position);
            }
            if(!positions.isEmpty()){
                positions = positionRepository.saveAll(positions);
            }
        }
        return BackMessage.success().putData(positionMapper.dto(positions));
    }

    @Override
    public BackMessage searchAllOfNoUse(String depatmentId) {
        List<Position> positions = positionRepository.findNoUse(depatmentId);
        if(positions==null || positions.isEmpty()){
            positions = new ArrayList<>();
        }
        return BackMessage.success().putData(positionMapper.dto(positions));
    }
}
